package com.xuecheng.filesystem.service;

import com.alibaba.fastjson.JSONObject;
import com.xuecheng.filesystem.dao.FileSystemRepository;
import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import org.apache.commons.lang3.StringUtils;
import org.csource.fastdfs.StorageClient1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;


@Service
public class FileSystemService {
    @Autowired
    StorageClient1 storageClient1;
    @Autowired
    FileSystemRepository fileSystemRepository;



    /**
     * 文件上传
     * @param multipartFile
     * @param fileTag
     * @param businessKey
     * @param metaData
     * @return
     */
    public UploadFileResult upload(MultipartFile multipartFile,
                                   String fileTag,
                                   String businessKey,
                                   String metaData){
        // 1.上传文件，得到文件的id
        String fileId = fdFsUpload(multipartFile);
        if (StringUtils.isEmpty(fileId)){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        }
        // 2.将文件的id及其他信息存储到mongoDb
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFileId(fileId);
        fileSystem.setFilePath(fileId);
        fileSystem.setFiletag(fileTag);
        fileSystem.setBusinesskey(businessKey);
        fileSystem.setFileName(multipartFile.getOriginalFilename());
        fileSystem.setFileType(multipartFile.getContentType());
        if (StringUtils.isNotEmpty(metaData)){
            try {
                Map map = JSONObject.parseObject(metaData,Map.class);
                fileSystem.setMetadata(map);
            } catch (Exception e){
                e.printStackTrace();
            }
        }

        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS,fileSystem);

    }

    /**
     * fdfs上传
     * @param multipartFile
     * @return
     */
    private String fdFsUpload(MultipartFile multipartFile){
        try {
            byte[] bytes = multipartFile.getBytes();
            String originalFilename = multipartFile.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            if (StringUtils.isEmpty(extName)){
                extName = "";
            }
            //TODO 文件大小不能超过1M
            return storageClient1.upload_file1(bytes, extName, null);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        }
        return null;
    }


}
